
package cn.lili.modules.grab.alibaba.serviceimpl;

import cn.hutool.http.HttpUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.modules.file.client.UploadClient;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dto.GoodsOperationDTO;
import cn.lili.modules.goods.entity.enums.PurchaseRuleEnum;
import cn.lili.modules.goods.integration.GoodsIntegrationService;
import cn.lili.modules.grab.alibaba.mapper.GoodsGrabDetailMapper;
import cn.lili.modules.grab.alibaba.mapper.GoodsGrabMapper;
import cn.lili.modules.grab.alibaba.constant.GlobalTools;
import cn.lili.modules.grab.entity.dos.GoodsGrab;
import cn.lili.modules.grab.entity.dos.GoodsGrabDetail;
import cn.lili.modules.grab.entity.dto.GoodsGrabReqParam;
import cn.lili.modules.grab.entity.dto.alibaba.*;
import cn.lili.modules.grab.entity.vos.CollectGoodsData;
import cn.lili.modules.grab.alibaba.service.GoodsGrabService;
import cn.lili.modules.supplier.entity.dto.SupplierGoodsOperationDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class GoodsGrabServiceImpl extends ServiceImpl<GoodsGrabMapper, GoodsGrab>
        implements GoodsGrabService {

    @Autowired
    private GoodsGrabDetailMapper goodsGrabDetailMapper;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private GoodsIntegrationService goodsIntegrationService;

    @Autowired
    private UploadClient uploadClient;


    public void updateGoodsGrab(String grabId, Integer status) {
        GoodsGrab grab = this.getById(grabId);
        if (null != grab) {

            int $total_num = grab.getTotalNum() + 1;
            int $success_num = grab.getSuccessNum();
            int $error_num = grab.getErrorNum();

            if (status == 1) {
                $success_num += 1;
            } else {
                $error_num += 1;
            }
            grab.setErrorNum($error_num);
            grab.setSuccessNum($success_num);
            grab.setTotalNum($total_num);

            this.updateById(grab);
        }
    }

    @Transactional
    @Override
    public String goodsGrab(GoodsGrabReqParam grabReqParam) {

        String siteId = UserContext.getCurrentUser().getId();

        //String siteId = grabReqParam.getSite_id();
        String grabId = grabReqParam.getGrab_id();
        String url = grabReqParam.getUrl();

        if (StringUtil.isEmpty(grabId)) {
            return "缺少参数grab_id";
        }
        if (StringUtil.isEmpty(url)) {
            return "商品链接不能为空";
        }

        try {
            //判断链接合法性
            if (!GlobalTools.is_url(url)) {
                GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                goodsGrabDetail.setSiteId(siteId);
                goodsGrabDetail.setGrabId(grabId);
                goodsGrabDetail.setUrl(url);
                goodsGrabDetail.setReason("url地址不正确");
                goodsGrabDetail.setStatus(2);
                goodsGrabDetailMapper.insert(goodsGrabDetail);
                updateGoodsGrab(grabId, 2);
                return "url地址不正确";
            }
            //判断url类型  及 获取id
            URL urlObj = null;
            try {
                urlObj = new URL(url);
                String host = urlObj.getHost();
                Map<String, String> typeMap = GlobalTools.getUrlType(host);
                if (null == typeMap) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("不支持的商品链接");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "url地址不正确";
                }
                String id = "";
                String grabType = typeMap.get("type");
                if (grabType.equals("jd") || grabType.equals("1688")) {
                    String path = urlObj.getPath();
                    Pattern p = Pattern.compile("[^0-9]");
                    Matcher m = p.matcher(path);
                    id = m.replaceAll("").trim();
                } else {
                    Map<String, Object> queryMap = GlobalTools.convertUrlQuery(urlObj.getQuery());
                    if (null != queryMap && queryMap.containsKey("id")) {
                        id = (String) queryMap.get("id");
                    }
                }

                if (StringUtil.isEmpty(id)) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("不支持的商品链接");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "url地址不正确";
                }

                String api99Key = "86A3EEBE94E87596628E910E0CE7B0CA";
                String request_url = GlobalTools.getCollectUrl(grabType);
                Map<String, String> param = new HashMap<>();
                param.put("apikey", api99Key);
                param.put("itemid", id);

                String result = HttpUtil.get(request_url + "?apikey=" + api99Key + "&itemid=" + id);
                log.debug("==============grab result ==>" + result);
                AlibabaGoodsGrabRespParam respParam = JSON.parseObject(result, AlibabaGoodsGrabRespParam.class);
                if (null == respParam) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("采集失败");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "采集失败";
                }
                //Map<String, Object> resultMap = JSON.parseObject(result, Map.class);
                if (!respParam.getRetcode().equals("0000")) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason(respParam.getMessage());
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return respParam.getMessage();
                }
                CollectGoodsData collectGoodsData = null;
                switch (grabType) {
                    case "taobao":
                        collectGoodsData = taobaoHandleData(null, siteId);
                        break;
                    case "tmall":
                        collectGoodsData = tmallHandleData(null, siteId);
                        break;
                    case "jd":
                        collectGoodsData = jdHandleData(null, siteId);
                        break;
                    case "1688":
                        collectGoodsData = alibabaHandleData(respParam, siteId);
                        break;
                }
                if (null == collectGoodsData || StringUtil.isEmpty(collectGoodsData.getGoods_name())) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("采集失败");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "采集失败";
                }

                collectGoodsData.setCategory_id(grabReqParam.getCategory_id());
                collectGoodsData.setCategory_json(grabReqParam.getCategory_json());
                collectGoodsData.setIs_virtual(grabReqParam.getIs_virtual());
                collectGoodsData.setOut_url(url);

                Map<String, GoodsSpec> goodsSpecMap = collectGoodsData.getSkuMap();
                if (null == goodsSpecMap || goodsSpecMap.isEmpty()) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("采集失败，商品无sku数据");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "采集失败，商品无sku数据";
                }

                String goodsPrice = collectGoodsData.getPrice();
                if (StringUtil.isEmpty(goodsPrice)) {
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("采集失败，商品无价格");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "采集失败，商品无价格";
                }


                SupplierGoodsOperationDTO supplierGoodsOperationDTO = new SupplierGoodsOperationDTO();
                supplierGoodsOperationDTO.setCategoryPathSon(grabReqParam.getCategoryPathSon());
                supplierGoodsOperationDTO.setCategoryPathSonName(grabReqParam.getCategoryPathSonName());
                supplierGoodsOperationDTO.setGoodsName(collectGoodsData.getGoods_name());
                supplierGoodsOperationDTO.setGoodsUnit(collectGoodsData.getUnit());
                supplierGoodsOperationDTO.setCategoryPath(grabReqParam.getCategory_id());
                supplierGoodsOperationDTO.setRelease(false);
                String goodsType = "PHYSICAL_GOODS";
                if (grabReqParam.getIs_virtual() == 1) {
                    goodsType = "VIRTUAL_GOODS";
                }
                supplierGoodsOperationDTO.setGoodsType(goodsType);
                supplierGoodsOperationDTO.setPurchaseRule(PurchaseRuleEnum.SKU);
                supplierGoodsOperationDTO.setPrice(Double.parseDouble(collectGoodsData.getPrice()));
                supplierGoodsOperationDTO.setIntro(collectGoodsData.getGoods_content());
                supplierGoodsOperationDTO.setGoodsVideo(collectGoodsData.getVideo_url());
                supplierGoodsOperationDTO.setGoodsFrom(2);
                supplierGoodsOperationDTO.setGoodsGrabUrl(url);
                supplierGoodsOperationDTO.setSalesModel("RETAIL");
                supplierGoodsOperationDTO.setGoodsGalleryList(collectGoodsData.getImageList());
                supplierGoodsOperationDTO.setSupportProxy(true); //支持代发
                supplierGoodsOperationDTO.setSupportPurchase(false); //不支持采购

                List<SkuProps> skuPropsList = collectGoodsData.getSkuPropsList();
                if(null==skuPropsList || skuPropsList.size()<1){
                    GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                    goodsGrabDetail.setSiteId(siteId);
                    goodsGrabDetail.setGrabId(grabId);
                    goodsGrabDetail.setUrl(url);
                    goodsGrabDetail.setReason("采集失败，商品无sku数据");
                    goodsGrabDetail.setStatus(2);
                    goodsGrabDetailMapper.insert(goodsGrabDetail);
                    updateGoodsGrab(grabId, 2);
                    return "采集失败，商品无sku数据";
                }
                SkuProps existImageProps = null;


                List<Map<String, Object>> skuMapList = new ArrayList<>();

                //查找包含图片的sku
                for (SkuProps one : skuPropsList) {
                    List<SkuValue> skuValues = one.getValue();
                    if (skuValues.stream().anyMatch(v -> StringUtil.isNotEmpty(v.getImageUrl()))) {
                        existImageProps = one;
                        break;
                    }
                }
                //商品的sku列表没有包含图片的数据，则取一个sku的数据，并填充相册中的第一张图片
                if(null==existImageProps){
                    String skuImg = collectGoodsData.getImageList().get(0).matches("^(http|https).*?")
                            ? collectGoodsData.getImageList().get(0)
                            : collectGoodsData.getGoods_image();//取相册中的第一条记录作为sku的图片
                    SkuProps defaultOne = skuPropsList.get(0);
                    List<SkuValue> skuValues = defaultOne.getValue();
                    skuValues.forEach(e -> e.setImageUrl(skuImg));
                    existImageProps = defaultOne;
                }

                if (null != existImageProps) {
                    List<SkuValue> skuValues = existImageProps.getValue();
                    for (SkuValue v : skuValues) {
                        Map<String, Object> skuItem = new HashMap<>();
                        skuItem.put(GoodsSku.IMAGES_KEY, v.getImageUrl());
                        skuItem.put("specName", v.getName());
                        Map<String, Object> specJson = new HashMap<>();
                        specJson.put(existImageProps.getProp(), v.getName());
                        skuItem.put("specJson", JSON.toJSONString(specJson));
                        skuMapList.add(skuItem);
                    }

                    SkuProps existImageProps1 = existImageProps;
                    List<SkuProps> leftSkuPropsList = skuPropsList.stream().filter(item -> !item.getFid().equals(existImageProps1.getFid())).collect(Collectors.toList());
                    if (null != leftSkuPropsList && !leftSkuPropsList.isEmpty()) {
                        for (SkuProps one : leftSkuPropsList) {
                            List<SkuValue> skuValues1 = one.getValue();
                            List<Map<String, Object>> skuMapTemp = new ArrayList<>();
                            for (SkuValue skuv : skuValues1) {
                                for (Map map : skuMapList) {
                                    Map<String, Object> skuItem = new HashMap<>();
                                    String specName = (String) map.get("specName") + " " + skuv.getName();
                                    skuItem.put(GoodsSku.IMAGES_KEY, (String) map.get(GoodsSku.IMAGES_KEY));
                                    skuItem.put("specName", specName);
                                    Map<String, Object> specJson = JSON.parseObject((String) map.get("specJson"));
                                    specJson.put(one.getProp(), skuv.getName());
                                    skuItem.put("specJson", JSON.toJSONString(specJson));
                                    skuMapTemp.add(skuItem);
                                }
                            }
                            skuMapList = skuMapTemp;
                        }
                    }
                }
                List<Map<String, Object>> skuMapList1 = skuMapList;
                log.debug("=====skuMapList>>>>" + JSON.toJSONString(skuMapList));
                //商品的sku数据
                List<Map<String, Object>> skuList = new ArrayList<>();

                /**
                 * 将sku数据按规格组合顺序回填相关字段
                 */
                List<String> specKeyList = goodsSpecMap.keySet().stream().toList();
                for (Map<String, Object> existMap : skuMapList1) {
                    GoodsSpec goodsSpec = null;
                    String name = (String) existMap.get("specName");
                    for(String specName : specKeyList){
                        String specName1 = specName.replace("&gt;", " ");
                        if (specName1.equals(name)) {
                            goodsSpec = goodsSpecMap.get(specName);
                            break;
                        }
                    }
                    if (null != goodsSpec) {
                        Map<String, Object> objectMap = new HashMap<>();
                        String skuPrice = goodsPrice;
                        if (null != goodsSpec.getDiscountPrice() && !"".equals(goodsSpec.getDiscountPrice())) {
                            objectMap.put(GoodsSku.COST_KEY, goodsSpec.getDiscountPrice());
                            skuPrice = goodsSpec.getDiscountPrice();
                        } else {
                            objectMap.put(GoodsSku.COST_KEY, goodsPrice);
                        }
                        objectMap.put(GoodsSku.SN_KEY, goodsSpec.getSkuId());
                        objectMap.put(GoodsSku.PRICE_KEY, skuPrice); //默认的sku价格，
                        objectMap.put(GoodsSku.QUANTITY_KEY, goodsSpec.getCanBookCount());
                        objectMap.put(GoodsSku.WEIGHT_KEY, 1);
                        String skuImage = (String) existMap.get(GoodsSku.IMAGES_KEY);
                        if (StringUtil.isNotEmpty(skuImage)) {
                            //skuImage = uploadImage(skuImage);
                            Map<String, String> imageMap = new HashMap<>();
                            imageMap.put("url", skuImage);
                            List<Map<String, String>> imageList = new ArrayList<>();
                            imageList.add(imageMap);
                            objectMap.put(GoodsSku.IMAGES_KEY, imageList);
                        }
                        Map<String, Object> specJson = JSON.parseObject((String) existMap.get("specJson"), Map.class);
                        specJson.forEach((kk, vv) -> {
                            objectMap.put(kk, vv);
                        });
                        skuList.add(objectMap);
                    }
                }

//                goodsSpecMap.forEach((specName, goodsSpec) -> {
//                    Map<String, Object> existMap = null;
//                    for (Map<String, Object> skuMap : skuMapList1) {
//                        String name = (String) skuMap.get("specName");
//                        String specName1 = specName.replace("&gt;", " ");
//                        log.debug("=====specName1>>>>name>>>>>>" + specName1 + ">>>" + name + ">>>>" + specName1.contains(name));
//
//                        if (specName1.contains(name)) {
//                            existMap = skuMap;
//                            break;
//                        }
//                    }
//                    if (null != existMap) {
//                        Map<String, Object> objectMap = new HashMap<>();
//                        String skuPrice = goodsPrice;
//                        if (null != goodsSpec.getDiscountPrice() && !"".equals(goodsSpec.getDiscountPrice())) {
//                            objectMap.put(GoodsSku.COST_KEY, goodsSpec.getDiscountPrice());
//                            skuPrice = goodsSpec.getDiscountPrice();
//                        } else {
//                            objectMap.put(GoodsSku.COST_KEY, goodsPrice);
//                        }
//                        objectMap.put(GoodsSku.SN_KEY, goodsSpec.getSkuId());
//                        objectMap.put(GoodsSku.PRICE_KEY, skuPrice); //默认的sku价格，
//                        objectMap.put(GoodsSku.QUANTITY_KEY, goodsSpec.getCanBookCount());
//                        objectMap.put(GoodsSku.WEIGHT_KEY, 1);
//                        String skuImage = (String) existMap.get(GoodsSku.IMAGES_KEY);
//                        if (StringUtil.isNotEmpty(skuImage)) {
//                            //skuImage = uploadImage(skuImage);
//                            Map<String, String> imageMap = new HashMap<>();
//                            imageMap.put("url", skuImage);
//                            List<Map<String, String>> imageList = new ArrayList<>();
//                            imageList.add(imageMap);
//                            objectMap.put(GoodsSku.IMAGES_KEY, imageList);
//                        }
//                        Map<String, Object> specJson = JSON.parseObject((String) existMap.get("specJson"), Map.class);
//                        specJson.forEach((kk, vv) -> {
//                            objectMap.put(kk, vv);
//                        });
//                        skuList.add(objectMap);
//                    }
//                });
//
//
                supplierGoodsOperationDTO.setSkuList(skuList);

                log.debug("=====采集商品入库数据>>>>" + JSON.toJSONString(supplierGoodsOperationDTO));

                //添加商品
                goodsIntegrationService.saveSupplierGoods(supplierGoodsOperationDTO);

                GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
                goodsGrabDetail.setSiteId(siteId);
                goodsGrabDetail.setGrabId(grabId);
                goodsGrabDetail.setUrl(url);
                goodsGrabDetail.setReason("");
                goodsGrabDetail.setStatus(1);
                goodsGrabDetailMapper.insert(goodsGrabDetail);
                updateGoodsGrab(grabId, 1);
                return null;


            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        GoodsGrabDetail goodsGrabDetail = new GoodsGrabDetail();
        goodsGrabDetail.setSiteId(siteId);
        goodsGrabDetail.setGrabId(grabId);
        goodsGrabDetail.setUrl(url);
        goodsGrabDetail.setReason("采集失败");
        goodsGrabDetail.setStatus(2);
        goodsGrabDetailMapper.insert(goodsGrabDetail);
        updateGoodsGrab(grabId, 2);
        return "采集失败";

    }

    @Override
    public GoodsOperationDTO getGoodsOperationDTO(String url) {
        return null;
    }

    @Override
    public String isDown(Goods goods) {
        return null;
    }

    @Override
    public void transferImageToOss(Goods goods) {

    }

    @Override
    public SupplierGoodsOperationDTO getSupplierGoodsOperationDTO(String url) {
        try {
            SupplierGoodsOperationDTO supplierGoodsOperationDTO = new SupplierGoodsOperationDTO();
            //判断链接合法性
            if (!GlobalTools.is_url(url)) {
                throw new ServiceException("url地址不正确");
            }
            //判断url类型  及 获取id
            URL urlObj = null;
            urlObj = new URL(url);
            String host = urlObj.getHost();
            Map<String, String> typeMap = GlobalTools.getUrlType(host);
            String id = "";
            String grabType = typeMap.get("type");
            if (grabType.equals("jd") || grabType.equals("1688")) {
                String path = urlObj.getPath();
                Pattern p = Pattern.compile("[^0-9]");
                Matcher m = p.matcher(path);
                id = m.replaceAll("").trim();
            } else {
                Map<String, Object> queryMap = GlobalTools.convertUrlQuery(urlObj.getQuery());
                if (null != queryMap && queryMap.containsKey("id")) {
                    id = (String) queryMap.get("id");
                }
            }

            String api99Key = "86A3EEBE94E87596628E910E0CE7B0CA";
            String request_url = GlobalTools.getCollectUrl(grabType);
            Map<String, String> param = new HashMap<>();
            param.put("apikey", api99Key);
            param.put("itemid", id);

            String result = HttpUtil.get(request_url + "?apikey=" + api99Key + "&itemid=" + id);
            log.debug("==============grab result ==>" + result);
            AlibabaGoodsGrabRespParam respParam = JSON.parseObject(result, AlibabaGoodsGrabRespParam.class);
            CollectGoodsData collectGoodsData = new CollectGoodsData();
            switch (grabType) {
                case "taobao":
                    collectGoodsData = taobaoHandleData(null, null);
                    break;
                case "tmall":
                    collectGoodsData = tmallHandleData(null, null);
                    break;
                case "jd":
                    collectGoodsData = jdHandleData(null, null);
                    break;
                case "1688":
                    collectGoodsData = alibabaHandleData(respParam, null);
                    break;
            }

            supplierGoodsOperationDTO.setGoodsName(collectGoodsData.getGoods_name());
            supplierGoodsOperationDTO.setGoodsUnit(collectGoodsData.getUnit());
            supplierGoodsOperationDTO.setRelease(false);
            supplierGoodsOperationDTO.setGoodsVideo(collectGoodsData.getVideo_url());
            supplierGoodsOperationDTO.setPurchaseRule(PurchaseRuleEnum.SKU);
            supplierGoodsOperationDTO.setPrice(Double.parseDouble(collectGoodsData.getPrice()));
            supplierGoodsOperationDTO.setIntro(collectGoodsData.getGoods_content());
            supplierGoodsOperationDTO.setGoodsFrom(2);
            supplierGoodsOperationDTO.setGoodsGrabUrl(url);
            supplierGoodsOperationDTO.setSalesModel("RETAIL");
            supplierGoodsOperationDTO.setGoodsGalleryList(collectGoodsData.getImageList());
            supplierGoodsOperationDTO.setSupportProxy(true); //支持代发
            supplierGoodsOperationDTO.setSupportPurchase(false); //不支持采购

            List<SkuProps> skuPropsList = collectGoodsData.getSkuPropsList();
            SkuProps existImageProps = null;


            List<Map<String, Object>> skuMapList = new ArrayList<>();

            //查找包含图片的sku
            for (SkuProps one : skuPropsList) {
                List<SkuValue> skuValues = one.getValue();
                if (skuValues.stream().anyMatch(v -> StringUtil.isNotEmpty(v.getImageUrl()))) {
                    existImageProps = one;
                    break;
                }
            }
            //商品的sku列表没有包含图片的数据，则取一个sku的数据，并填充相册中的第一张图片
            if (null == existImageProps) {
                String skuImg = collectGoodsData.getImageList().get(0);//取相册中的第一条记录作为sku的图片
                SkuProps defaultOne = skuPropsList.get(0);
                List<SkuValue> skuValues = defaultOne.getValue();
                skuValues.forEach(e -> e.setImageUrl(skuImg));
                existImageProps = defaultOne;
            }

            if (null != existImageProps) {
                List<SkuValue> skuValues = existImageProps.getValue();
                for (SkuValue v : skuValues) {
                    Map<String, Object> skuItem = new HashMap<>();
                    skuItem.put(GoodsSku.IMAGES_KEY, v.getImageUrl());
                    skuItem.put("specName", v.getName());
                    Map<String, Object> specJson = new HashMap<>();
                    specJson.put(existImageProps.getProp(), v.getName());
                    skuItem.put("specJson", JSON.toJSONString(specJson));
                    skuMapList.add(skuItem);
                }

                SkuProps existImageProps1 = existImageProps;
                List<SkuProps> leftSkuPropsList = skuPropsList.stream().filter(item -> !item.getFid().equals(existImageProps1.getFid())).collect(Collectors.toList());
                if (null != leftSkuPropsList && !leftSkuPropsList.isEmpty()) {
                    for (SkuProps one : leftSkuPropsList) {
                        List<SkuValue> skuValues1 = one.getValue();
                        List<Map<String, Object>> skuMapTemp = new ArrayList<>();
                        for (SkuValue skuv : skuValues1) {
                            for (Map map : skuMapList) {
                                Map<String, Object> skuItem = new HashMap<>();
                                String specName = (String) map.get("specName") + " " + skuv.getName();
                                skuItem.put(GoodsSku.IMAGES_KEY, (String) map.get(GoodsSku.IMAGES_KEY));
                                skuItem.put("specName", specName);
                                Map<String, Object> specJson = JSON.parseObject((String) map.get("specJson"));
                                specJson.put(one.getProp(), skuv.getName());
                                skuItem.put("specJson", JSON.toJSONString(specJson));
                                skuMapTemp.add(skuItem);
                            }
                        }
                        skuMapList = skuMapTemp;
                    }
                }
            }

            String goodsPrice = collectGoodsData.getPrice();
            Map<String, GoodsSpec> goodsSpecMap = collectGoodsData.getSkuMap();
            List<Map<String, Object>> skuMapList1 = skuMapList;
            log.debug("=====skuMapList>>>>" + JSON.toJSONString(skuMapList));
            //商品的sku数据
            List<Map<String, Object>> skuList = new ArrayList<>();
            goodsSpecMap.forEach((specName, goodsSpec) -> {
                Map<String, Object> existMap = null;
                for (Map<String, Object> skuMap : skuMapList1) {
                    String name = (String) skuMap.get("specName");
                    String specName1 = specName.replace("&gt;", " ");
                    log.debug("=====specName1>>>>name>>>>>>" + specName1 + ">>>" + name + ">>>>" + specName1.contains(name));

                    if (specName1.equals(name)) {
                        existMap = skuMap;
                        break;
                    }
                }

                if (null != existMap) {
                    Map<String, Object> objectMap = new HashMap<>();
                    if (null != goodsSpec.getDiscountPrice() && !"".equals(goodsSpec.getDiscountPrice())) {
                        objectMap.put(GoodsSku.COST_KEY, goodsSpec.getDiscountPrice());
                    } else {
                        objectMap.put(GoodsSku.COST_KEY, goodsPrice);
                    }
                    objectMap.put(GoodsSku.SN_KEY, goodsSpec.getSkuId());
                    //objectMap.put(GoodsSku.COST_KEY, goodsPrice);
                    objectMap.put(GoodsSku.QUANTITY_KEY, goodsSpec.getCanBookCount());
                    objectMap.put(GoodsSku.WEIGHT_KEY, 10);
                    String skuImage = (String) existMap.get(GoodsSku.IMAGES_KEY);
                    if (StringUtil.isNotEmpty(skuImage)) {
                        //skuImage = uploadImage(skuImage);
                        Map<String, String> imageMap = new HashMap<>();
                        imageMap.put("url", skuImage);
                        List<Map<String, String>> imageList = new ArrayList<>();
                        imageList.add(imageMap);
                        objectMap.put(GoodsSku.IMAGES_KEY, imageList);
                    }
                    Map<String, Object> specJson = JSON.parseObject((String) existMap.get("specJson"), Map.class);
                    specJson.forEach((kk, vv) -> {
                        objectMap.put(kk, vv);
                    });
                    skuList.add(objectMap);
                }
            });

            supplierGoodsOperationDTO.setSkuList(skuList);

            log.debug("=====采集商品入库数据>>>>" + JSON.toJSONString(supplierGoodsOperationDTO));
            return supplierGoodsOperationDTO;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("定时采集失败{}" + e.getMessage());
            return null;
        }
    }

    /**
     * 淘宝数据处理
     */
    public CollectGoodsData taobaoHandleData(JSONObject $params, String $site_id) {
        return new CollectGoodsData();
    }

    /**
     * 天猫数据处理
     */
    public CollectGoodsData tmallHandleData(JSONObject $params, String $site_id) {
        return new CollectGoodsData();
    }

    /**
     * 京东数据处理
     */
    public CollectGoodsData jdHandleData(JSONObject $params, String $site_id) {
        return new CollectGoodsData();
    }

    /**
     * 1688数据处理
     */
    public CollectGoodsData alibabaHandleData(AlibabaGoodsGrabRespParam respParam, String $site_id) {
        Random random = new Random();
        CollectGoodsData data = new CollectGoodsData();
        try {
            GoodsDetail goodsDetail = respParam.getData();
            if (null != goodsDetail) {
                data.setGoods_name(goodsDetail.getTitle()); //名称
                data.setUnit(goodsDetail.getUnit()); //单位
                data.setSite_id($site_id); //供应商ID
                data.setVideo_url(goodsDetail.getVideoUrl());
                if (!goodsDetail.getSkuProps().isEmpty()) {
                    for (int i = 0, len = goodsDetail.getSkuProps().size(); i < len; i++) {
                        SkuProps skuProps = goodsDetail.getSkuProps().get(i);
                        String specId = (i + 1) + "" + random.nextInt(1, 99) + "" + random.nextInt(1, 999);
                        skuProps.setSpecId(specId);
                        for (int j = 0, len1 = skuProps.getValue().size(); j < len1; j++) {
                            String specValueId = (j + 1) + "" + random.nextInt(1, 999) + "" + random.nextInt(1, 99);
                            SkuValue skuValue = skuProps.getValue().get(j);
                            skuValue.setSpec_id(specId);
                            skuValue.setSpec_name(skuProps.getSpecName());
                            skuValue.setSpec_value_id(specValueId);
                            skuProps.getValue().set(j, skuValue);
                        }
                        goodsDetail.getSkuProps().set(i, skuProps);
                    }
                }

                String[] $priceArray = goodsDetail.getDisplayPrice().split("-");
                String price = $priceArray[0].replace("￥", "");
                data.setPrice(price);

                //组合商品sku
                Map<String, GoodsSpec> skuMap = goodsDetail.getSkuMap();
                data.setSkuMap(skuMap);
                data.setSkuPropsList(goodsDetail.getSkuProps());
                data.setGoods_content(goodsDetail.getDesc());
                List<String> imgList = new ArrayList<>();
//                goodsDetail.getImages().forEach(item->{
//                    String result = uploadImage(item);
//                    if(null!=result){
//                        imgList.add(result);
//                    }
//                });
                imgList = goodsDetail.getImages();
                data.setImageList(imgList);

                //详情图片转换
                //               List<String> descImgList = new ArrayList<>();
//                goodsDetail.getDescImgs().forEach(item->{
//                    String result = uploadImage(item);
//                    if(null!=result){
//                        descImgList.add(result);
//                    }
//                });
                StringBuilder descContent = new StringBuilder();
                descContent.append("<p>");
                goodsDetail.getDescImgs().forEach(item -> {
                    descContent.append("<img src=\"" + item + "\" />");
                });
                descContent.append("</p>");
                data.setGoods_content(descContent.toString());

                //data.setGoods_content(goodsDetail.getDesc());
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String uploadImage(String imgUrl) {
        return uploadClient.upload(imgUrl);
    }


}